package com.intretech.tj.mqtt.element;

import com.intretech.tj.global.parent.VerticleParent;
import com.intretech.tj.mqtt.MQTTConfig;
import com.intretech.tj.mqtt.MQTTHandler;
import com.intretech.tj.mqtt.OutLog;
import io.smallrye.mutiny.Uni;
import io.vertx.mqtt.MqttServerOptions;
import io.vertx.mutiny.mqtt.MqttServer;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;

import static com.intretech.tj.mqtt.OutLog.TCPElementStart;

@Slf4j
@ApplicationScoped
public class MQTTElement extends VerticleParent {
    private final OutLog outLog;

    private final MQTTConfig config;

    private final MQTTHandler MQTTHandler;

    @Inject
    public MQTTElement(OutLog outLog, MQTTConfig config, MQTTHandler MQTTHandler) {
        this.outLog = outLog;
        this.config = config;
        this.MQTTHandler = MQTTHandler;
    }

    @Override
    public Uni<Void> asyncStart() {
        return MqttServer.create(vertx, new MqttServerOptions()
                        .setReceiveBufferSize(1250000)
                        .setMaxMessageSize(1250000)
                        .setPort(config.port()))
                .endpointHandler(endpoint -> MQTTHandler.endpointHandler(endpoint, false))
                .listen()
                .invoke(() -> log.info(outLog.getMessage(TCPElementStart)))
                .replaceWithVoid();
    }
}
